package com.dmai.capacity.platform.oauth.controller;

import java.util.List;
import java.util.Map;

import com.dmai.capacity.platform.common.model.OauthClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.common.exception.BusinessException;
import com.dmai.capacity.platform.oauth.common.service.IOauthClientService;
import com.dmai.capacity.platform.oauth.dto.OauthClientDto;

import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;

/**
 * 应用相关接口
 */
@Slf4j
@RestController
@RequestMapping("/clients")
public class ClientController {
    @Autowired
    private IOauthClientService clientService;

    @GetMapping("/list")
    public PageResult<OauthClient> list(@RequestParam Map<String, Object> params) {
        return clientService.listClient(params, true);
    }

    @GetMapping("/{id}")
    public OauthClient getById(@PathVariable Long id) {
        return clientService.getById(id);
    }


    @GetMapping("/client")
    public OauthClient getByClientId(@RequestParam String clientId) {
        return clientService.loadClientByClientId(clientId, null);
    }

    @GetMapping("/all")
    public ResponseEntity<List<OauthClient>> allClient() {
        PageResult<OauthClient> page = clientService.listClient(Maps.newHashMap(), false);
        return ResponseEntity.succeed(page.getData());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable Long id) {

        Try.of(() -> clientService.delClient(id)).onFailure(ex -> log.error("client-delete-error", ex))
                .getOrElseThrow(item -> new BusinessException("操作失败"));
        return ResponseEntity.succeed("操作成功");

    }

    @PostMapping("/saveOrUpdate")
    public ResponseEntity saveOrUpdate(@RequestBody OauthClientDto clientDto) throws Exception {

        Try.of(() -> clientService.saveClient(clientDto)).onFailure(ex -> log.error("client-saveOrUpdate-error", ex))
                .getOrElseThrow(item -> new BusinessException("操作失败"));
        return ResponseEntity.succeed("操作成功");

    }
}
